<template>
  <el-dialog
    title="添加车辆"
    :visible.sync="dialogVisible"
    width="828px"
    class="dialogTitle"
    @closed="dialogClosed('addForm')"
  >
    <el-form label-width="140px" ref="addForm" :model="dialogData" :rules="rules">
      <el-form-item label="车辆联系人" prop="carContacts">
        <el-input v-model.trim="dialogData.carContacts"></el-input>
        <!-- <el-select
          v-model="dialogData.carContacts"
          placeholder="请选择"
          clearable
          class="form-select"
        >
          <el-option
            v-for="item in dialogData.carContactOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="车辆联系人联系方式" prop="carContactsPhone">
        <el-input v-model.trim="dialogData.carContactsPhone"></el-input>
      </el-form-item>
      <el-form-item label="车辆联系人身份证号" prop="carContactsIDNumber">
        <el-input v-model.trim="dialogData.carContactsIDNumber"></el-input>
      </el-form-item>
      <el-form-item label="车 牌 号 码" prop="carPhone">
        <el-input v-model.trim="dialogData.carPhone"></el-input>
      </el-form-item>
      <el-form-item label="车 辆 颜 色" prop="carColor">
        <el-input v-model.trim="dialogData.carColor"></el-input>
        <!-- <el-select v-model="dialogData.carColor" placeholder="请选择" clearable class="form-select">
          <el-option
            v-for="item in dialogData.carColorOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <!-- <el-form-item label="手 机 号 码" prop="phone">
        <el-input v-model.trim="dialogData.phone"></el-input>
      </el-form-item> -->
      <el-form-item label="车 辆 类 型" prop="carTypeValue">
        <el-input v-model.trim="dialogData.carTypeValue"></el-input>
        <!-- <el-select v-model="dialogData.carTypeValue" class="form-select" clearable>
          <el-option
            v-for="item in dialogData.carType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="证件有效期" prop="validityTime">
        <!-- <el-input v-model.trim="dialogData.validityTime"></el-input> -->
        <!-- <el-date-picker
          v-model="dialogData.validityTime"
          type="datetime"
          placeholder="选择日期时间"
          align="right"
          class="datePicker"
          :picker-options="dialogData.pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker> -->
        <el-date-picker
          v-model="dialogData.validityTime"
          align="right"
          type="date"
          class="datePicker"
          placeholder="选择日期"
          :picker-options="dialogData.pickerOptions"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="荷载" prop="loadCapacity">
        <label slot="label">荷&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;载</label>
        <el-input type="number" v-model.trim.number="dialogData.loadCapacity"></el-input>
      </el-form-item>
      <el-form-item label="轴数" prop="axesNum">
        <label slot="label">轴&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数</label>
        <el-input type="number" v-model.trim="dialogData.axesNum"></el-input>
      </el-form-item>
      <el-form-item label="所 属 企 业" prop="enterprise">
        <el-input v-model.trim="dialogData.enterprise"></el-input>
        <!-- <el-select v-model="dialogData.enterprise" class="form-select" clearable>
          <el-option
            v-for="item in dialogData.enterpriseOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="车 辆 状 态" prop="carStatusValue">
        <el-select v-model="dialogData.carStatusValue" class="form-select" clearable>
          <el-option
            v-for="item in dialogData.carStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" class="spacingL" prop="remarks">
        <label slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label>
        <el-input v-model.trim="dialogData.remarks"></el-input>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <cs-btn
        type="primary"
        @click.native="confirmBtnClick('addForm')"
        btnText="确定"
        class="confirm_btn dialog_btn"
        :buttonStatus="buttonStatus"
      />
      <cs-btn @click.native="cancelBtnClick('addForm')" btnText="取消" class="dialog_btn" />
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash'

import csBtn from '@/components/cs-btn/cs-btn.vue'
import { addCar, searchCarNum } from '@/service/operate/cart_manage/cart_manage'
// import { getAllEnterpriseName } from '@/service/source_manage/enterprise_manage'
// import { getContactsName } from '@/service/operate/user_manage/user_manage'
import {
  isCarNumCorrect,
  isNumber,
  isPhoneCorrect,
  isIDNumberCorrect
} from '@/utils/regularVerification'

export default {
  components: {
    csBtn
  },
  data() {
    // 自定义校验规则
    const isCarNumRepeat = async (rule, value, callback) => {
      try {
        // 查询车牌号是否重复
        const { code, data } = await searchCarNum({ carNumber: _.toUpper(value) })
        if (code === 0) {
          callback()
        } else {
          callback(new Error('车牌号已存在'))
        }
      } catch (err) {
        console.log(err)
        console.log(value)
        this.$message.error('服务器出错了')
      }
    }
    const carNumCorrectVerification = async (rule, value, callback) => {
      // 验证车牌号是否正确
      if (isCarNumCorrect(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的车牌号'))
      }
    }
    const mustBeANumber = async (rule, value, callback) => {
      // 验证车牌号是否正确
      if (isNumber(value)) {
        callback()
      } else {
        callback(new Error('请输入0-9的数字'))
      }
    }
    const phoneCorrectVerification = async (rule, value, callback) => {
      // 验证手机号是否正确
      if (value) {
        if (isPhoneCorrect(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的手机号'))
        }
      } else {
        callback()
      }
    }
    const IDNumberCorrectVerification = async (rule, value, callback) => {
      // 验证身份证号是否正确
      if (value) {
        if (isIDNumberCorrect(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的身份证号'))
        }
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      buttonStatus: false,
      dialogData: {
        // carContacts: '',
        // carContactOption: [],
        carContactsPhone: '',
        carContactsIDNumber: '',
        carPhone: '',
        carColor: '',
        // carColorOption: [
        //   {
        //     value: '蓝色',
        //     label: '蓝色'
        //   },
        //   {
        //     value: '黄色',
        //     label: '黄色'
        //   },
        //   {
        //     value: '绿色',
        //     label: '绿色'
        //   }
        // ],
        // phone: '',
        // carType: [
        //   {
        //     value: '执法suv车',
        //     label: '执法suv车'
        //   },
        //   {
        //     value: '执法轿车',
        //     label: '执法轿车'
        //   }
        // ],
        carTypeValue: '',
        validityTime: '',
        pickerOptions: {
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date())
              }
            },
            {
              text: '昨天',
              onClick(picker) {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24)
                picker.$emit('pick', date)
              }
            },
            {
              text: '一周前',
              onClick(picker) {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', date)
              }
            }
          ]
        },
        loadCapacity: '',
        axesNum: '',
        enterprise: '',
        // enterpriseOption: [],
        carStatus: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '异常'
          }
        ],
        carStatusValue: '',
        remarks: ''
      },
      rules: {
        // carContacts: [{ required: true, message: '请输入车辆联系人名称', trigger: 'blur' }],
        carContactsPhone: [{ validator: phoneCorrectVerification, trigger: 'blur' }],
        carContactsIDNumber: [{ validator: IDNumberCorrectVerification, trigger: 'blur' }],
        carPhone: [
          { required: true, message: '请输入车牌号码', trigger: 'blur' },
          { validator: isCarNumRepeat, trigger: 'blur' },
          { validator: carNumCorrectVerification, trigger: 'blur' }
        ],
        // phone: [{ validator: phoneCorrectVerification, trigger: 'blur' }],
        // enterprise: [{ required: true, message: '请选择所属企业', trigger: 'blur' }],
        axesNum: [
          { required: true, message: '请输入轴数', trigger: 'blur' },
          { validator: mustBeANumber, trigger: 'blur' }
        ],
        loadCapacity: [
          { required: true, message: '请输入荷载', trigger: 'blur' },
          { validator: mustBeANumber, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.$bus.$on('addCartDialogVisible', () => {
      this.dialogVisible = true
    })
    // 获取所有企业名称
    // this.getAllEnterpriseName()
    // 查询所有车辆联系人
    // this.getContactsName()
  },
  beforeDestroy() {
    this.$bus.$off('addCatSuccess')
  },
  methods: {
    // 对话框关闭事件
    dialogClosed(formName) {
      this.resetForm(formName)
    },
    confirmBtnClick(formName) {
      this.buttonStatus = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 新增车辆
            const { code, data } = await addCar({
              // 车辆联系人
              contactsName: this.dialogData.carContacts,
              contactsPhone: this.dialogData.carContactsPhone,
              contactsIdCard: this.dialogData.carContactsIDNumber,
              // 车牌号码
              vehicleNumber: _.toUpper(this.dialogData.carPhone),
              // 车辆颜色
              color: this.dialogData.carColor,
              // 手机号码
              // phone: this.dialogData.phone,
              // 车辆类型
              vehicleType: this.dialogData.carTypeValue,
              // 证件有效期
              expireDate: this.dialogData.validityTime,
              // 荷载
              loadCapacity: this.dialogData.loadCapacity,
              // 轴数
              axleCount: this.dialogData.axesNum,
              // 所属企业
              companyName: this.dialogData.enterprise,
              // 车辆状态
              state: this.dialogData.carStatusValue,
              remark: this.dialogData.remarks,
              permId: 133
            })
            console.log({ code, data })
            if (code === 0) {
              this.$bus.$emit('addCatSuccess')
              this.$message({
                message: '添加车辆成功',
                type: 'success'
              })
              this.dialogVisible = false
              setTimeout(() => {
                this.buttonStatus = false
              }, 500)
              this.resetForm(formName)
            }
          } catch (err) {
            console.log('err:', err)
            this.$message.error('添加车辆失败')
            this.buttonStatus = false
          }
        } else {
          this.buttonStatus = false
        }
      })
    },
    cancelBtnClick(formName) {
      this.dialogVisible = false
      this.resetForm(formName)
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
    // 获取所有企业名称
    // async getAllEnterpriseName() {
    //   try {
    //     const { data } = await getAllEnterpriseName()
    //     console.log(data)
    //     if (data.code === 0) {
    //       data.data.forEach((item) => {
    //         // 拼接所属企业选项
    //         this.dialogData.enterpriseOption.push({
    //           value: item,
    //           label: item
    //         })
    //       })
    //     }
    //   } catch (err) {
    //     console.log(err)
    //     this.$message.error('服务器出错了')
    //   }
    // }
    // 查询所有车辆联系人
    // async getContactsName() {
    //   try {
    //     const { data } = await getContactsName()
    //     if (data.code === 0) {
    //       // 遍历所有责任人数据，组成下拉框选项数据
    //       data.data.forEach((item) => {
    //         this.dialogData.carContactOption.push({ value: item, label: item })
    //       })
    //     }
    //   } catch (err) {
    //     console.log(err)
    //     this.$message.error('服务器出错了')
    //   }
    // }
  }
}
</script>

<style scoped>
.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-form-item >>> .el-form-item__label {
  color: #888888;
}

/* 更改el-select下拉框图标的行高 */
.el-select >>> .el-input__icon {
  line-height: 32px;
}

/* 更改el-select下拉框的图标 */
.el-select >>> .el-icon-arrow-up:before {
  content: '\e78f';
}

.form-select {
  width: 100%;
}

.dialogTitle >>> .el-dialog {
  padding: 6px 10px 18px 10px !important;
}

.datePicker {
  width: 100%;
}
</style>
